package com.example.userservice.controller;

import com.example.userservice.dto.UserDTO;
import com.example.userservice.service.UserService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    @PostMapping("/user/register")
    public ResponseEntity<UserDTO> register(@RequestBody UserDTO userDTO) {
        return ResponseEntity.ok(userService.register(userDTO));
    }

    @PostMapping("/user/login")
    public ResponseEntity<String> login(@RequestParam String username, @RequestParam String password) {
        return ResponseEntity.ok(userService.login(username, password));
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<UserDTO> getUserInfo(@PathVariable Long userId, HttpServletRequest request) {
        String roleCode = (String) request.getAttribute("roleCode");
        Object currentUserIdObj = request.getAttribute("userId");
        Long currentUserId = currentUserIdObj == null ? null : Long.valueOf(currentUserIdObj.toString());
        return ResponseEntity.ok(userService.getUserInfo(userId, roleCode, currentUserId));
    }

    @GetMapping("/users")
    public ResponseEntity<PageInfo<UserDTO>> getUserList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        String roleCode = (String) request.getAttribute("roleCode");
        Object userIdObj = request.getAttribute("userId");
        Long userId = userIdObj == null ? null : Long.valueOf(userIdObj.toString());
        return ResponseEntity.ok(userService.getUserList(pageNum, pageSize, roleCode, userId));
    }

    @PutMapping("/user/{userId}")
    public ResponseEntity<UserDTO> updateUser(
            @PathVariable Long userId,
            @RequestBody UserDTO userDTO,
            HttpServletRequest request) {
        String roleCode = (String) request.getAttribute("roleCode");
        Object currentUserIdObj = request.getAttribute("userId");
        Long currentUserId = currentUserIdObj == null ? null : Long.valueOf(currentUserIdObj.toString());
        return ResponseEntity.ok(userService.updateUser(userId, userDTO, roleCode, currentUserId));
    }

    @PostMapping("/user/reset-password")
    public ResponseEntity<Void> resetPassword(
            @RequestParam Long userId,
            @RequestParam String newPassword,
            HttpServletRequest request) {
        String roleCode = (String) request.getAttribute("roleCode");
        Object currentUserIdObj = request.getAttribute("userId");
        Long currentUserId = currentUserIdObj == null ? null : Long.valueOf(currentUserIdObj.toString());
        userService.resetPassword(userId, newPassword, roleCode, currentUserId);
        return ResponseEntity.ok().build();
    }

    /**
     * 测试分布式事务：用户注册
     */
    @PostMapping("/register-with-transaction")
    public ResponseEntity<String> registerWithTransaction(@RequestBody UserDTO userDTO) {
        try {
            userService.registerUserWithTransaction(userDTO);
            return ResponseEntity.ok("用户注册成功（分布式事务）");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("用户注册失败（事务回滚）: " + e.getMessage());
        }
    }

    /**
     * 测试本地事务：用户更新
     */
    @PutMapping("/update-with-transaction")
    public ResponseEntity<String> updateWithTransaction(@RequestBody UserDTO userDTO) {
        try {
            userService.updateUserWithLocalTransaction(userDTO);
            return ResponseEntity.ok("用户更新成功（本地事务）");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("用户更新失败（事务回滚）: " + e.getMessage());
        }
    }
}
